<?php

/**
 * IndexController - The default controller class
 * 
 * @author
 * @version 
 */

require_once('Extension/Controller/Action.php');

class Admin_SearchLuceneController extends Extension_Controller_Action 
{
    public function init() {
    }

    /**
	 * The default action - show the home page
	 */
    public function indexAction() 
    {
        $this->render();
    }

    public function memberAction() {
        
        if ($this->getRequest()->isPost()) {
            
            $keywords = $this->getRequest()->getParam('keywords');
            
            if (!empty($keywords)) {

                require_once('Zend/Search/Lucene/Document.php');
                require_once('Zend/Search/Lucene/Field.php');
                require_once('Zend/Search/Lucene/Analysis/Analyzer.php');
                require_once('Model/Function/User.php');
                
                $functionUser = new Model_Function_User();
                $users = $functionUser->getAllUsers();
                $luceneIndex = Zend_Registry::get('luceneIndex');
                $encoding = Zend_Registry::get('luceneEncoding');

                foreach ($users as $user) {
                    $doc = new Zend_Search_Lucene_Document();
                    $doc->addField(Zend_Search_Lucene_Field::UnIndexed('user_id', $user->user_id, $encoding));
                    $doc->addField(Zend_Search_Lucene_Field::Keyword('user_name', $user->user_name, $encoding));
                    $doc->addField(Zend_Search_Lucene_Field::Text('user_email', $user->user_email, $encoding));
                    $doc->addField(Zend_Search_Lucene_Field::UnStored('summary', $user->user_status, $encoding));
                    $luceneIndex->addDocument($doc);
                }
                $luceneIndex->optimize();

                Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding($encoding);
                $term = new Zend_Search_Lucene_Index_Term('*'.$keywords.'*');
                $queryString = new Zend_Search_Lucene_Search_Query_Wildcard($term);

                $hits = $luceneIndex->find($queryString);
                $result = false;
                if (is_array($hits) and !empty($hits)) {
                    $result = $hits;
                }
                $this->view->result = $result;
            }
        }
    }

    public function optimizeAction() {
        if (Zend_Registry::isregistered('luceneIndex')) {
            $luceneIndex = Zend_Registry::get('luceneIndex');
            $luceneIndex->optimize();
        }
        //$this->_redirect($this->view->baseUrl);
    }


}